<template>
  <div class="comSelect-container">
    <Tree
      :options="treeData"
      v-model="innerValue"
      :placeholder="placeholder"
      clearable
      :disabled="disabled"
      v-on="$listeners"
      lastLevel
      lastLevelKey="type"
      :multiple="multiple"
      lastLevelValue="position"
      :field="field"
      :post="true"
      @TreeData="treeData = $event"
    >
    </Tree>
  </div>
</template>

<script>
import Tree from "@/components/Myselectxy/Tree";
import { Bus } from "../eventBus.js";
export default {
  name: "posSelect",
  components: {
    Tree,
  },
  props: ["value", "disabled", "placeholder", "multiple", "field"],
  model: {
    prop: "value",
    event: "input",
  },
  data() {
    return {
      treeData: [],
      innerValue: this.value,
      id: "",
      Data: this.$store.state.base.postTreeData,
    };
  },
  mounted() {
    Bus.$on("handleTest", (id, val) => {
      this.getData(id, val);
    });
  },
  methods: {
    async getData(id, val) {
      if (id && val) {
        var names = this.$store.state.base.myTree[id];
        this.treeData = await this.$store.dispatch("base/getPositionTree");
        this.treeData = this.treeData[0].children
          .map((item) => {
            if (item.children) {
              return item.children.find((val) => val.fullName === names);
            }
          })
          .filter((item) => item !== undefined);
        if (this.treeData.length) {
          this.treeData = this.treeData[0].children;
        }
      } else {
        this.treeData = await this.$store.dispatch("base/getPositionTree");
      }
      if (!this.treeData) this.treeData = [];
      if (id === this.field) {
        this.Data[this.field] = this.treeData;
        this.$store.commit("base/setPostTreeData", this.Data);
      }
    },
  },

  created() {
    this.getData();
  },
  watch: {
    innerValue(val) {
      val && this.$emit("change", val);
      val && Bus.$emit("change", val, this.field);
    },
    value(val) {
      this.innerValue = val;
    },
  },
};
</script>
<style lang="scss">
.comSelect-container {
  .el-select {
    width: 100%;
  }
}
</style>